package com.ctgu.chatapp.Netty.Handler

import java.util.*

class ExponentialBackOffRetry(baseSleepTimeMs: Int, private val maxRetries: Int, maxSleepMs: Int) :
    RetryPolicy {
    private val random = Random()
    private val baseSleepTimeMs: Long = baseSleepTimeMs.toLong()
    private val maxSleepMs: Int = maxSleepMs
    override fun allowRetry(retryCount: Int): Boolean {
        return retryCount < maxRetries
    }

    override fun getSleepTimeMs(retrycount: Int): Long {
        var retryCount = retrycount
        if (retryCount > MAX_RETRIES_LIMIT) {
            retryCount = MAX_RETRIES_LIMIT
        }
        var sleepMs = baseSleepTimeMs * Math.max(1, random.nextInt(1 shl retryCount))
        if (sleepMs > maxSleepMs) {
            sleepMs = maxSleepMs.toLong()
        }
        return sleepMs
    }

    companion object {
        private const val MAX_RETRIES_LIMIT = 29
    }

}